<!-- ID 姓名、性别、年龄、身份证号码、电话号码、居住地址-->
<template>
  <div class="button-container">
    <!--  添加客户按钮-->
    <el-button type="success" @click="save()" :icon="CirclePlusFilled" size="default">
      增加客户
    </el-button>
  </div>
  <br><br>
  <!--  添加/修改表单-->
  <el-dialog v-model="tableData.dialogFormVisible" :before-close="handleClose" :title="tableData.isAdd?'增加信息':'修改信息'" width="40%">
    <el-form  :model="tableData.customer" :rules="rules" ref="formRef" label-width="auto"  style="max-width: 500px;">
      <el-row>
        <el-form-item label="姓名" style="margin-left: 35px" prop="customerName" :rules="rules.customerName">
          <el-input v-model="tableData.customer.customerName" autocomplete="off" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="性别" prop="customerSex" :rules="rules.customerSex" style="margin-left: 35px">
          <el-radio-group v-model="tableData.customer.customerSex" @change="handleGenderChange">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="年龄" prop="customerAge" :rules="rules.customerAge" style="margin-left: 35px">
          <el-input type="number"  v-model="tableData.customer.customerAge" autocomplete="off" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="身份证号码" prop="customerCard" :rules="rules.customerCard" style="margin-left: 35px">
          <el-input v-model="tableData.customer.customerCard" autocomplete="off" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="电话号码" prop="customerPhone" :rules="rules.customerPhone" style="margin-left: 35px">
          <el-input v-model="tableData.customer.customerPhone" autocomplete="off" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="居住地址" prop="customerAddress" style="margin-left: 35px">
          <el-input v-model="tableData.customer.customerAddress" autocomplete="off" />
        </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm()">
          保存数据
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 查询的表单数据 -->
  <el-form :inline="true" :model="tableData.customerArr" class="demo-form-inline">

    <el-form-item label="客户姓名">
      <el-input v-model="tableData.likeCustomerName" placeholder="模糊查询" clearable />
    </el-form-item>
    <el-form-item label="客户电话">
      <el-input v-model="tableData.likeCustomerPhone" placeholder="后四位" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="load()" :icon="Search">查询</el-button>
    </el-form-item>
  </el-form>

  <!--  客户信息表-->
  <el-table :data="tableData.customerArr" style="width: 100%">

    <el-table-column label="序号" width="80" >
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.$index + 1 + (tableData.pageNum-1)*tableData.pageSize}}</div>
          </template>
          <template #reference>
            <el-tag class="large-font">{{ scope.$index + 1 + (tableData.pageNum-1)*tableData.pageSize}}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="ID" width="80" >
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.customerId }}</div>
          </template>
          <template #reference>
            <el-tag class="large-font">{{ scope.row.customerId }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="姓名" width="90">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.customerName }}</div>
          </template>
          <template #reference>
            <el-tag class="large-font">{{ scope.row.customerName }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="性别" width="80">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{scope.row.customerSex}}</div>
          </template>
          <template #reference>
            <el-tag class="large-font">{{ scope.row.customerSex===1?"男":"女" }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="年龄" width="80">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.customerAge }}</div>
          </template>
          <template #reference>
            <el-tag class="large-font">{{ scope.row.customerAge }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="身份证号码" width="200" >
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.customerCard }}</div>
          </template>
          <template #reference>
            <el-tag class="large-font" >{{ scope.row.customerCard }}</el-tag>
          </template>
        </el-popover>
      </template>

    </el-table-column>


    <el-table-column label="电话号码" width="150">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.customerPhone }}</div>
          </template>
          <template #reference>
            <el-tag class="large-font">{{ scope.row.customerPhone }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="居住地址" width="200">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.customerAddress }}</div>
          </template>
          <template #reference>
            <el-tag class="large-font">{{ scope.row.customerAddress }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope" >
        <el-button
            size="small"
            type="warning"
            @click="handleEdit(scope.row)"
        >
          修改
        </el-button>
        <el-popconfirm @confirm="handleDelete(scope.row.customerId)" title="确定删除数据?">
          <template #reference>
            <el-button
                size="small"
                type="danger"
            >删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>

  </el-table>

  <!--分页展示-->
  <br/>
  <!--  current-page:当前页码
      page-size：步长
      total： 自动计算总页数
      @size-change:步长发生改变时触发函数
      @current-change：当前页发生变化  触发函数
-->
  <el-config-provider :locale="zhCn">
    <el-pagination
        v-model:current-page="tableData.pageNum"
        v-model:page-size="tableData.pageSize"
        :page-sizes="[5, 7, 9, 15]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next"
        :total="tableData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-config-provider>

</template>

<script setup>
import {reactive,ref} from "vue";
import axios from 'axios';
import {ElMessage} from "element-plus";
// 引入中文包
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { CirclePlusFilled,Search } from '@element-plus/icons-vue';

const formRef = ref(null);
// 表单验证失败时显示错误信息，选择后清除
const handleGenderChange = () => {
  if (formRef.value.customerSex !== null) {
    formRef.value.clearValidate('customerSex'); // 清除特定字段的验证状态
  }
};
//身份证验证规则
const validateCard = (rule, value, callback) => {
  if (value && value.length === 18) {
    // 这里可以添加更复杂的身份证号码验证逻辑
    callback();
  } else {
    callback(new Error('身份证号码必须是18位'));
  }
};
//电话号码验证规则
const validatePhone = (rule, value, callback) => {
  if (value && value.length === 11) {
    // 这里可以添加电话号码格式的正则表达式验证
    callback();
  } else {
    callback(new Error('电话号码必须是11位'));
  }
};
const rules = ref({
  customerName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度必须在2到10个字符之间', trigger: 'blur' }
  ],
  customerSex: [
    { required: true, message: '请选择性别', trigger: 'blur' },
  ],
  customerAge: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value && (value < 1 || value > 150)) {
          return callback(new Error('年龄必须在1到150之间'));
        }
        callback();
      }, trigger: 'blur' }
  ],
  customerCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { validator: validateCard, trigger: 'blur' }
  ],
  customerPhone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  customerAddress:[
    { required: true, message: '请填写地址', trigger: 'blur' },
  ]
  // 其他字段的验证规则...
});

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 这里可以添加保存数据的逻辑
      persistence()
    } else {
      console.error('表单验证失败!');
    }
  });
};

const tableData = reactive({
  customerArr:[
    {id:"1",customerId:"1001",customerName:"张三",customerSex:"1",customerAge:"18",
      customerCard:"500381xxxxxxxx4175", customerPhone:"177xxxxxxxx",customerAddress:"重庆市南岸区"},
  ],//存放客户信息数组
  dialogFormVisible: false,//窗口控制，默认关闭
  isAdd:true,//默认添加，否则修改
  customer:{},//临时客户实体
  likeCustomerName:"",//模糊查询客户姓名
  likeCustomerPhone:"",//模糊查询客户电话号码
  pageNum: 1, //全局当前页
  pageSize: 5, //全局每页大小
  total: 0, //全局总条数
})
// 将客户信息加载到表格中
function load(){
  axios({
    method:"get",
    url:"http://localhost:8080/boot/customer/getAllCustomerLikeNameAndPhoneAndPageHelper",
    params:{
      customerName:tableData.likeCustomerName,
      customerPhone:tableData.likeCustomerPhone,
      pageNum:tableData.pageNum,
      pageSize:tableData.pageSize,
    }
  }).then((result)=>{
    let pageInfo = result.data;
    tableData.customerArr=pageInfo.list;
    tableData.total=pageInfo.total;
  })
}
//执行load()
load()
//添加用户接口
function save(){
  tableData.dialogFormVisible = true
  tableData.isAdd = true
}
//关闭表单
function handleClose(){
  tableData.dialogFormVisible = false
  tableData.customer={}
  formRef.value.resetFields();
}
//点击修改按钮操作进行回显
//两种方式：1、主键回显 2 直接赋值，这里使用方式2
const handleEdit = (row) => {
  tableData.isAdd = false
  //1.先根据id查询最新的数据
  tableData.customer.id = row.id
  tableData.customer.customerId = row.customerId
  tableData.customer.customerName = row.customerName
  tableData.customer.customerSex = row.customerSex
  tableData.customer.customerAge = row.customerAge
  tableData.customer.customerCard = row.customerCard
  tableData.customer.customerPhone = row.customerPhone
  tableData.customer.customerAddress = row.customerAddress
  //弹窗
  tableData.dialogFormVisible = true
}
//保存数据
function persistence(){
  if(tableData.isAdd){
    Add()
  }else {
    update()
  }
}
//添加客户信息
function Add(){
  //保存
  axios({
    method:"get",
    url:"http://localhost:8080/boot/customer/insertCustomer",
    params:tableData.customer
  }).then((result)=>{
    if(result.data){
      ElMessage.success("添加成功");
    }else {
      ElMessage.error("添加失败");
    }
    handleClose()
    load()
  });
}
//更新客户接口
function update(){
  //修改
  axios({
    method:"get",
    url:"http://localhost:8080/boot/customer/updateCustomer",
    params:tableData.customer
  }).then((result)=>{
    if(result.data){
      ElMessage.success("修改成功");
    }else {
      ElMessage.error("修改失败");
    }
    handleClose()
    load()
  });
}
//分页点击页码处理的方法
const handleCurrentChange = (number) => {
  tableData.pageNum = number //将点击的页码赋值给全局定义的当前页
  //再次重新查询
  load()
}
//处理当前每页多少条数据
const handleSizeChange = (number) => {
  tableData.pageSize = number
  load()
}

//删除
function handleDelete(index){
  axios({
    method: "get",
    url: "http://localhost:8080/boot/customer/deleteCustomerById",
    params:{
      customerId:index
    }
  }).then((result)=>{
    if(result){
      ElMessage.success("删除成功")
    }else {
      ElMessage.error("删除失败")
    }
    load()
  })
}
</script>

<style>
.large-font {
  font-size: 14px; /* table字体大小，你可以根据需要调整这个值 */
  color: forestgreen;
}
.button-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

</style>


